package com.icez.demo

import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.DragEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.isVisible

/**
 * 手机控制器
 * @sample
 * @author Icez
 */
class PhoneControlView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs), View.OnDragListener {

    companion object {
        const val DRAG_PIC = "phone_control_pic"
        const val DRAG_WIDTH = "phone_control_width"
        const val DRAG_HEIGHT = "phone_control_height"
    }

    // 手机画笔
    private val mPhonePaint = Paint(Paint.ANTI_ALIAS_FLAG)


    // 手机画笔宽度
    private val mPhonePaintWidth = 1f

    // 手机外补丁
    private val mPhoneMargin = 50f

    private val mDashPathEffect = DashPathEffect(floatArrayOf(10f, 10f), 0f)

    // 手机区域
    private val mPhoneRectF = RectF()

    // 手机外圆角
    private val mPhoneRadius = 50f

    // 手机状态懒的高度
    private val mStatusBarHeight = 80f

    // 手机底部栏的高度
    private val mNavigationBarHeight = 50f

    // 摄像头宽度
    private val mCameraWidth = 150f

    // 摄像头高度
    private val mCameraHeight = 50f

    private val mCameraBgColor = Color.BLACK

    // 布局内补丁
    private val mLayoutPadding = 10f

    private val mLayoutBgColor = Color.GRAY

    // 操作按钮宽度
    private val mOptionWidth = 300f
    private val mOptionHeight = 25f

    private val mPhoneBgColor = Color.WHITE

    private val mOptionBgColor = Color.GRAY

    private var frameLayout: FrameLayout? = null

    private var mLayoutRectF = RectF()

    // 子控件的范围
    private var mRectList = ArrayList<Rect>()

    // 拖动的控件
    private var mDragView: CircleButton? = null

    // 适配器
    private var mPhoneControlAdapter: PhoneControlAdapter? = null

    init {
        setWillNotDraw(false)
        mPhonePaint.style = Paint.Style.STROKE
        mPhonePaint.strokeWidth = mPhonePaintWidth

        frameLayout = FrameLayout(context)
        frameLayout?.setBackgroundColor(Color.GRAY)
        frameLayout?.setOnDragListener(this)
        addView(frameLayout)

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        mLayoutRectF.left = mPhoneMargin + mLayoutPadding
        mLayoutRectF.right = width - mPhoneMargin - mLayoutPadding
        mLayoutRectF.top =
            mPhoneMargin + (mStatusBarHeight / 2f - mCameraHeight / 2f) + mCameraHeight + (mStatusBarHeight / 2f - mCameraHeight / 2f)
        mLayoutRectF.bottom = height - mPhoneMargin - mNavigationBarHeight
        setMeasuredDimension(width, height)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        Log.e("icez", "布局控件")

        frameLayout?.layout(
            mLayoutRectF.left.toInt(),
            mLayoutRectF.top.toInt(),
            mLayoutRectF.right.toInt(),
            mLayoutRectF.bottom.toInt()
        )

        for (i in 0 until (frameLayout?.childCount ?: 0)) {
            val rect = mRectList[i]
            frameLayout?.getChildAt(i)?.layout(
                rect.left,
                rect.top,
                rect.right,
                rect.bottom
            )
        }

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        mPhonePaint.style = Paint.Style.FILL
        mPhonePaint.color = mPhoneBgColor
        mPhonePaint.pathEffect = null
        mPhoneRectF.left = mPhoneMargin
        mPhoneRectF.right = width - mPhoneMargin
        mPhoneRectF.top = mPhoneMargin
        mPhoneRectF.bottom = height - mPhoneMargin
        canvas?.drawRoundRect(mPhoneRectF, mPhoneRadius, mPhoneRadius, mPhonePaint)

        mPhonePaint.style = Paint.Style.FILL
        mPhonePaint.color = mCameraBgColor
        mPhonePaint.pathEffect = null
        mPhoneRectF.left = width / 2f - mCameraWidth / 2f
        mPhoneRectF.right = mPhoneRectF.left + mCameraWidth
        mPhoneRectF.top = mPhoneRectF.top + (mStatusBarHeight / 2f - mCameraHeight / 2f)
        mPhoneRectF.bottom = mPhoneRectF.top + mCameraHeight
        canvas?.drawRoundRect(mPhoneRectF, mCameraHeight / 2f, mCameraHeight / 2f, mPhonePaint)

        mPhonePaint.style = Paint.Style.STROKE
        mPhonePaint.color = mLayoutBgColor
        mPhonePaint.pathEffect = mDashPathEffect
//        mPhoneRectF.left = mPhoneMargin + mLayoutPadding
//        mPhoneRectF.right = width - mPhoneMargin - mLayoutPadding
//        mPhoneRectF.top = mPhoneRectF.bottom + (mStatusBarHeight / 2f - mCameraHeight / 2f)
//        mPhoneRectF.bottom = height - mPhoneMargin - mNavigationBarHeight

        canvas?.drawRect(mLayoutRectF, mPhonePaint)

        mPhonePaint.style = Paint.Style.FILL
        mPhonePaint.color = mOptionBgColor
        mPhonePaint.pathEffect = null
        mPhoneRectF.left = width / 2f - mOptionWidth / 2f
        mPhoneRectF.right = mPhoneRectF.left + mOptionWidth
        mPhoneRectF.top =
            height - mPhoneMargin - (mNavigationBarHeight / 2f - mOptionHeight / 2 + mOptionHeight)
        mPhoneRectF.bottom = height - mPhoneMargin - (mNavigationBarHeight / 2f - mOptionHeight / 2)
        canvas?.drawRoundRect(mPhoneRectF, mPhoneRadius, mPhoneRadius, mPhonePaint)
    }

    /**
     * 设置适配器
     *
     * @param mPhoneControlAdapter
     */
    public fun setPhoneControlAdapter(mPhoneControlAdapter: PhoneControlAdapter) {
        this.mPhoneControlAdapter = mPhoneControlAdapter
    }


    /**
     * 获取子控件的布局访问,添加例子如下
     *
     *for (i in 0 until (frameLayout?.childCount ?: 0)) {
     *  val rect = mRectList[i]
     *  frameLayout?.getChildAt(i)?.layout(
     *      rect.left,
     *      rect.top,
     *      rect.right,
     *      rect.bottom
     *  )
     *}
     *
     * @return
     */
    public fun getChildLayoutRectList(): ArrayList<Rect> {
        return mRectList
    }

    override fun onDrag(p0: View?, event: DragEvent?): Boolean {
        when (event?.action) {
            DragEvent.ACTION_DRAG_STARTED -> {
                // 开始拖动
                Log.e("icez", "开始拖动")
                mDragView?.isVisible = false
            }
            DragEvent.ACTION_DRAG_ENTERED -> {
                // 进入
                Log.e("icez", "开始进入")
            }
            DragEvent.ACTION_DRAG_EXITED -> {
                // 移出
                Log.e("icez", "拖动移出")
            }
            DragEvent.ACTION_DRAG_ENDED -> {
                // 停止拖动
                Log.e("icez", "停止拖动")
            }
            DragEvent.ACTION_DRAG_LOCATION -> {
                // 停留
                Log.e("icez", "拖动停留")
            }
            DragEvent.ACTION_DROP -> {
                // 释放拖动
                Log.e("icez", "释放拖动")

                val intent = event.clipData.getItemAt(0).intent
                val pic = intent.getIntExtra(DRAG_PIC, 0)
                val width = intent.getIntExtra(DRAG_WIDTH, 0)
                val height = intent.getIntExtra(DRAG_HEIGHT, 0)
                val imageView = CircleButton(context)
                imageView.setImageResource(pic)
                val lp = LayoutParams(width, height)
                imageView.layoutParams = lp
                imageView.setOnLongClickListener {
                    mDragView = it as CircleButton?
                    val intent = Intent()
                    intent.putExtra(DRAG_PIC, R.mipmap.offered_play)
                    intent.putExtra(DRAG_HEIGHT, it.measuredHeight)
                    intent.putExtra(DRAG_WIDTH, it.measuredWidth)
                    Util.instance.setDrag(intent, it)
                    true
                }
                val touchX = event.x
                val touchY = event.y
                val rect = Rect()
                rect.left = (touchX - width / 2f).toInt()
                rect.right = (touchX + width / 2f).toInt()
                rect.top = (touchY - height / 2f).toInt()
                rect.bottom = (touchY + height / 2f).toInt()
                imageView.tag = rect
                mPhoneControlAdapter?.setChildViewStyle(imageView)
                mRectList.add(rect)
                frameLayout?.addView(imageView)

                if (mDragView != null) {
                    mRectList.remove(mDragView?.tag)
                    frameLayout?.removeView(mDragView)
                    mDragView = null
                }

                requestLayout()
            }
        }
        return true
    }
}